package org.jupiter.blog.common.utils;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.jupiter.blog.api.common.TreeNode;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class TreeUtils {

	public static <T extends TreeNode<T>> List<T> buildTree(List<T> nodes, String rootParentUuid) {
		if (nodes == null || nodes.isEmpty()){
			return Collections.emptyList();
		}

		// 1. 建立 parentUuid -> children 的映射
		Multimap<String, T> parentChildrenMap = ArrayListMultimap.create();
		for (T node : nodes){
			parentChildrenMap.put(node.getParentUuid(), node);
		}

		// 2. 递归构建树
		return buildChildren(parentChildrenMap, rootParentUuid);
	}

	private static <T extends TreeNode<T>> List<T> buildChildren(Multimap<String, T> parentChildrenMap,
			String parentUuid) {
		Collection<T> children = parentChildrenMap.get(parentUuid);
		if (CollectionUtils.isEmpty(children)){
			return Collections.emptyList();
		}

		return children.stream()
				.map(child -> {
					child.setChildren(buildChildren(parentChildrenMap, child.getUuid()));
					return child;
				})
				.collect(Collectors.toList());
	}

}
